package com.apes.scm.yy;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.repository.CustomRepository;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.jpa.spec.model.Filter;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import com.apes.scm.masterdata.contrast.model.ContrastPartyCode;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service("queryCommonService")
public class QueryCommonService extends DomainService {

    @Autowired
    private PartyRoleRepository partyRoleRepository;
    @Autowired
    private ContrastPartyCodeRepository contrastPartyCodeRepository;

    /**
     * 根据编码、其他单据查找__逻辑
     * @param simpleRequest
     * @return
     */
    public <T> T accordinNumberFindLogic(SimpleRequest simpleRequest, CustomRepository beanRepository, String[] customCondition, String idName, String excludesFields) {
        AtomicReference<String> atoValue = new AtomicReference<>();
        AtomicInteger atoIndex = new AtomicInteger(-1);

        Group group = JpaDsl.getGroup(simpleRequest);
        group.getFilters().stream().filter(filterObj -> {
            atoIndex.addAndGet(1);
            if (idName.equals(filterObj.getField())) {
                atoValue.set(String.valueOf(filterObj.getValue()));
            }
            return idName.equals(filterObj.getField());
        }).findAny();



        if (!StringUtils.isEmpty(atoValue.get())) { // 单号不为空
            group.getFilters().remove(atoIndex.get());

            // 排除不相干字段
            List<Filter> removeNotExistsFiled = group.getFilters().stream().filter(singleFilter -> !"excludesFields".equals(singleFilter.getField())).collect(Collectors.toList());
            group.getFilters().clear();
            group.setFilters(removeNotExistsFiled);

            for (int i = 0, iLen = customCondition.length; i < iLen; i++) {
                if (customCondition[i].contains("value")) customCondition[i] = atoValue.get();
            }
            List<Filter> filterList = JpaDsl.toFilter(customCondition);
            Group addNewGroups = new Group();
            addNewGroups.setOperator("or");
            addNewGroups.setFilters(filterList);

            group.addGroup(addNewGroups);
        }

        if (StringUtils.hasText(excludesFields)) return MapUtil.mapped(beanRepository.findAll(JpaDsl.build(group, true), JpaDsl.getPageable(simpleRequest)), excludesFields.split(","));
        Object object = beanRepository.findAll(JpaDsl.build(group, true), JpaDsl.getPageable(simpleRequest));
        return (T)object;
    }

    // 权限特殊处理
    public <T> T accordinNumberFindLogic2(SimpleRequest simpleRequest, CustomRepository beanRepository, List<Map> customCondition, List fixedColumn, String excludesFields) {
        List<Map> fixedColumnVArray = new ArrayList();
        List removeIndex = new ArrayList<>();

        // 配置列 和 值
        Group group = JpaDsl.getGroup(simpleRequest);
        fixedColumn.forEach(columnName -> {
            AtomicInteger atoIndex = new AtomicInteger(-1);
            group.getFilters().stream().filter(filterObj -> {
                atoIndex.set(atoIndex.get() + 1);
                if (columnName.equals(filterObj.getField())) {
                    Map fixedColumnV = new HashMap();
                    fixedColumnV.put(columnName, filterObj.getValue());
                    fixedColumnVArray.add(fixedColumnV);
                    removeIndex.add(filterObj);
                }
                return columnName.equals(filterObj.getField());
            }).findAny();
        });

        if (fixedColumnVArray.size() != 0) { // 单号不为空, 移除多余字段
            if (removeIndex.size() > 0) {
                removeIndex.forEach(indexs -> {
                    group.getFilters().remove(indexs);
                });
            }

            // 排除不相干字段
            List<Filter> removeNotExistsFiled = group.getFilters().stream().filter(singleFilter -> !"excludesFields".equals(singleFilter.getField())).collect(Collectors.toList());
            group.getFilters().clear();
            group.setFilters(removeNotExistsFiled);

            // 赋值
            customCondition.forEach(clumns -> {
                clumns.forEach((k, v) -> {
                    List<Map> columnNames = (List)v;
                    fixedColumnVArray.forEach(fixedColumnV -> {
                        fixedColumnV.forEach((k2, v2) -> {
                            if (k.equals(k2) ) {
                                for (int i = 0, iLen = columnNames.size(); i < iLen; i++) {
                                    if ("%%".equals(((HashMap) columnNames.get(i)).get("value"))) {
                                        ((HashMap) columnNames.get(i)).put("value", v2);
                                    }
                                }
                                List<Filter> filterList = new ArrayList();
                                for (Map<String, Object> row : columnNames) {
                                    filterList.add(Tools.toBean(Filter.class, row));
                                }
                                Group addNewGroups = new Group();
                                addNewGroups.setOperator("or");
                                addNewGroups.setFilters(filterList);
                                group.addGroup(addNewGroups);
                            }
                        });
                    });
                });
            });
        }

        if (StringUtils.hasText(excludesFields)) return MapUtil.mapped(beanRepository.findAll(JpaDsl.build(group, true), JpaDsl.getPageable(simpleRequest)), excludesFields.split(","));
        Object object = beanRepository.findAll(JpaDsl.build(group, true), JpaDsl.getPageable(simpleRequest));
        return (T)object;
    }

    /**
     * 根据编码获取对照供应商
     * @param partyRoleId
     */
    public String queryContrastPartyCodeGetGysid(String partyRoleId) {
        PartyRole partyRole = partyRoleRepository.findOne(partyRoleId);
        ContrastPartyCode getContrastPartyCode =
                contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("party.id", partyRole.getParty().getId()))
                        .stream().filter(contrastPartyCode -> StringUtils.hasText(contrastPartyCode.getGysid())).findFirst().orElse(null);
        if (getContrastPartyCode == null) {
            throw new RuntimeException("请配置角色对照表 供应商！");
        }
        return getContrastPartyCode.getGysid();
    }
}
